package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 员工管理业务层
 */
@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    private static final String LOGIN_ERROR = "login:error:";       // 错误次数 5 次以内
    private static final String LOGIN_LOCKED_HOUR = "login:lock:";  // 锁定 1 小时

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        // 1.获取登录信息
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        // 校验该用户是否被锁定
        Object flag = redisTemplate.opsForValue().get(LOGIN_LOCKED_HOUR + username);
        if(ObjectUtils.isNotEmpty(flag)) { // 该键不为空，则账户已被锁定
            log.info("账号被锁定，已被限制登录一小时");
            throw new AccountLockedException(MessageConstant.LOGIN_LOCKED_MESSAGE);
        }

        // 2.调用 mapper，查询用户信息
        Employee employee = employeeMapper.getByUsername(username);

        // 3.判断用户是否存在，如果不存在，返回错误信息
        if (employee == null) {
            log.info("所查询的员工信息为空");
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 4.判断用户密码是否正确，如果不正确，返回错误信息
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5Password.equals(employee.getPassword())) {
            log.info("密码错误");
            // 4.1 记录员工密码错误的标记，并设置有效时间为 5 分钟
            redisTemplate.opsForValue().set(getKey(username), "-", 300, TimeUnit.SECONDS);

            // 4.2 获取该员工的密码错误标记，如果标记的数量 >= 5, 则锁定账号 一小时
            Set<Object> keys = redisTemplate.keys(LOGIN_ERROR + username + ":*");
            if (keys != null && keys.size() >= 5) {
                log.info("该账号输入密码错误次数五分钟内超五次，已被锁定一小时");
                redisTemplate.opsForValue().set(LOGIN_LOCKED_HOUR + username, "-", 1, TimeUnit.HOURS);
                throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED_HOUR);
            }
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        // 5.校验用户账号是否禁用，如果禁用，返回错误信息
        if (StatusConstant.DISABLE == employee.getStatus()) {
            log.info("员工账号 {} 已禁用，禁止登录");
            throw new AccountLockedException(MessageConstant.ACCOUNT_DISABLED);
        }

        // 6.返回实体对象
        return employee;
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
        //1.补全实体属性
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(StatusConstant.ENABLE);  // 账号启用

//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        // 设置创建人和修改人
//        employee.setCreateUser(BaseContext.getCurrentId());     // 当前登录员工 id
//        employee.setUpdateUser(BaseContext.getCurrentId());     // 当前登录员工 id

        //2.调用 mapper，保存数据
        employeeMapper.insert(employee);
    }


    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        // 1.设置分页查询参数
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        // 2.调用 mapper 查询数据库,得到符合查询条件所有员工列表
        List<Employee> employeeList = employeeMapper.list(employeePageQueryDTO.getName());

        // 3.根据设置好的参数，将 employeeList 中符合分页条件的数据封装到 page 中
        Page<Employee> page = (Page<Employee>) employeeList;
        return new PageResult(page.getTotal(), page.getResult());
    }


    @Override
    public void enableOrDisable(Integer status, Long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
//                .updateTime(LocalDateTime.now())
//                .updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.update(employee);
    }

    @Override
    public void editEmployee(EmployeeDTO employeeDTO) {
        // 1.复制属性
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        // 2.补全此次修改时涉及到的字段
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        // 3.调用 mapper 动态更新
        employeeMapper.update(employee);
    }

    @Override
    public Employee getById(Long id) {
        // 1.调用 mapper 查询员工信息
        Employee employee = employeeMapper.query(id);
        return employee;
    }

    /**
     * 用户输入密码错误，生成 redis 中的 key
     * @param username
     * @return
     */
    private static String getKey(String username) {
        return LOGIN_ERROR + username + ":" + RandomStringUtils.randomAlphabetic(4);
    }
}
